import { computed } from 'vue'
import { useUserStore, type Role } from '@/stores/user'

export function usePerm() {
  const user = useUserStore()
  const role = computed<Role | null>(() => user.role)

  const isAdmin = computed(() => role.value === 'admin')
  const isEditor = computed(() => role.value === 'editor')
  const isViewer = computed(() => role.value === 'viewer')

  const canViewArticles = computed(() => !!role.value)
  const canEditArticles = computed(() => isAdmin.value || isEditor.value)
  const canPublishArticles = computed(() => isAdmin.value || isEditor.value)
  const canDeleteArticles = computed(() => isAdmin.value)

  const username = computed(() => user.name)

  const canEditArticle = (author: string) => {
    if (isAdmin.value) return true
    if (isEditor.value) return username.value === author
    return false
  }

  const canDeleteArticle = (author: string) => {
    if (isAdmin.value) return true
    if (isEditor.value) return username.value === author
    return false
  }
  const canManageUsers = computed(() => isAdmin.value)

  const hasRole = (roles?: Role[] | undefined) => {
    if (!roles || roles.length === 0) return true
    if (!role.value) return false
    return roles.includes(role.value)
  }

  return {
    role,
    isAdmin,
    isEditor,
    isViewer,
    canViewArticles,
    canEditArticles,
    canPublishArticles,
    canDeleteArticles,
    canManageUsers,
    username,
    canEditArticle,
    canDeleteArticle,
    hasRole
  }
}


